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> <!-- 使用組件,注意駝峰命名法轉化成短線 --> <!-- 向自組件傳數(shù)據 --> <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){ //經過變化的數(shù)組會作為第一個參數(shù)傳入 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'],//自組件接收數(shù)據 methods:{ onClickMe(){ console.log(this.msgfromfather); } } } </script> <style scoped> </style>
點擊按鈕之后效果圖如下:
總結
以上所述是小編給大家介紹的vue.js 父向子組件傳參的實例代碼,希望對大家有所幫助!
相關文章
vue中Echarts使用動態(tài)數(shù)據的兩種實現(xiàn)方式
這篇文章主要介紹了vue中Echarts使用動態(tài)數(shù)據的兩種實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10vue中控制mock在開發(fā)環(huán)境使用,在生產環(huán)境禁用方式
這篇文章主要介紹了vue中控制mock在開發(fā)環(huán)境使用,在生產環(huán)境禁用方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04