Home > Article > Web Front-end > Implementation method of vue.js parent passing parameters to child components
1. Create a new componentA.vue component with the following code:
store.js code is as follows:
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 code is as follows:
<template> <p 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> </p> </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 The .vue code is as follows:
<template> <p class="hello"> <h1>{{msg}}</h1> <h2>{{msgfromfather}}</h2> <button v-on:click="onClickMe">Click!</button> </p> </template> <<script> export default { data(){ return{ msg:'Hello form component a' } }, props:['msgfromfather'],//自组件接收数据 methods:{ onClickMe(){ console.log(this.msgfromfather); } } } </script> <style scoped> </style>
The rendering after clicking the button is as follows:
##Summary
The above is the detailed content of Implementation method of vue.js parent passing parameters to child components. For more information, please follow other related articles on the PHP Chinese website!