vue.js 父向子组件传参的实例代码
更新时间:2017年10月29日 11:44:54 作者:zjsfdx
这篇文章主要介绍了vue.js 父向子组件传参的实例代码,需要的朋友可以参考下
1.新建componentA.vue组件,代码如下:
store.js代码如下:
const STORAGE_KEY = 'todos-vue.js'
export default{
fetch(){
return JSON.parse(window.localStorage.getItem(STORAGE_KEY) || '[]')
},
save(items){
window.localStorage.setItem(STORAGE_KEY,JSON.stringify(items));
}
}
App.vue代码如下:
<template>
<div id="app">
<h1 v-text="title"></h1>
<input v-model="newItem" v-on:keyup.enter="addNew"/>
<ul>
<li v-for="item in items" v-bind:class="{finished:item.isFinished}" v-on:click='toogleFinish(item)'>
{{item.label}}
</li>
</ul>
<!-- 使用组件,注意驼峰命名法转化成短线 -->
<!-- 向自组件传数据 -->
<Component-a msgfromfather='you die!'></Component-a>
</div>
</template>
<script>
import Store from './store'
import ComponentA from './components/componentA' //该组件会被加载到该页面
export default {
name: 'app',
data () {
return {
title: 'this is a todo list',
items:Store.fetch(),
newItem:''
}
},
components:{ //注册组件
ComponentA
},
watch:{
items:{
handler(items){ //经过变化的数组会作为第一个参数传入
Store.save(items)
},
deep:true //深度复制
}
},
methods:{
toogleFinish(item){
item.isFinished = !item.isFinished
},
addNew(){
this.items.push({
label:this.newItem,
isFinished:false,
})
this.newItem = ''
}
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
.finished{
text-decoration: underline;
}
</style>
componentA.vue代码如下:
<template>
<div class="hello">
<h1>{{msg}}</h1>
<h2>{{msgfromfather}}</h2>
<button v-on:click="onClickMe">Click!</button>
</div>
</template>
<<script>
export default {
data(){
return{
msg:'Hello form component a'
}
},
props:['msgfromfather'],//自组件接收数据
methods:{
onClickMe(){
console.log(this.msgfromfather);
}
}
}
</script>
<style scoped>
</style>
点击按钮之后效果图如下:

总结
以上所述是小编给大家介绍的vue.js 父向子组件传参的实例代码,希望对大家有所帮助!
相关文章
vue2.0 中使用transition实现动画效果使用心得
这篇文章主要介绍了vue2.0 中使用transition实现动画效果使用心得,本文通过案例知识给大家介绍的非常详细,需要的朋友参考下吧2018-08-08
解决使用vue-awesome-swiper组件手动滚动点击失效问题
这篇文章主要介绍了使用vue-awesome-swiper组件手动滚动点击失效问题解决,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-06-06
Vue-router中hash模式与history模式的区别详解
这篇文章主要给大家介绍了关于Vue-router中hash模式与history模式区别的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2020-12-12


最新评论