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>
 <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.vue代码如下:
<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>
点击按钮之后效果图如下:
总结
以上就是vue.js父向子组件传参的实现方法的详细内容。
   
 
   