本篇内容介绍了“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">
<h2 v-text="title"></h2>
<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">
<h2>{{msg}}</h2>
<h3>{{msgfromfather}}</h3>
<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中如何实现父向子组件传参”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/4580264/blog/4356449