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>
点击按钮之后效果图如下:
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注创新互联成都网站设计公司行业资讯频道,感谢您对创新互联成都网站设计公司的支持。
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、网站设计器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
网站栏目:vue.js中怎么实现父向子组件传参-创新互联
链接地址:https://www.cdcxhl.com/article16/dphidg.html
成都网站建设公司_创新互联,为您提供建站公司、搜索引擎优化、虚拟主机、外贸建站、关键词优化、域名注册
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联