vue實現(xiàn)兩個組件之間數(shù)據(jù)共享和修改操作
我們在使用vue開發(fā)過程中會遇到這樣的情況,在父組件中引入了子組件,需要將父組件的值傳到子組件中顯示,同時子組件還可以更改父組件的值。
以我目前的一個項目的開發(fā)為例,如下圖頁面:
在父組件中,我引入了兩個子組件,一個是左邊的導航欄,還有中間的一個富文本編譯器組件,當我點擊左邊導航欄時,中間的頁面會切換,也就是改變引入的子組件。
怎么實現(xiàn)呢,首先,設置在該頁面index.vue中設置一個變量index,左邊導航欄每一項也對應一個index值,導航菜單綁定select函數(shù),@select='handleSelect',@是v-on的簡寫。
handleSelect函數(shù)接收到參數(shù),然后發(fā)射出去,再由父組件接收就可以了。
handleSelect(key, keyPath) { console.log(key, keyPath); this.changeIndex(keyPath[1]) }, changeIndex:function(key) { this.$emit('IndexChanged',key) }
this.$emit('IndexChanged',key)就是將key的值傳到一個叫IndexChanged函數(shù)中,
在index.vue綁定IndexChanged接收值,<Aside v-on:IndexChanged='change($event)'> </Aside>然后調用change函數(shù),注意$event是固定寫法,接收的就是子頁面?zhèn)鬟^來的key。然后就可以通過這個key改變index用來切換頁面了。
下面通過一個更加簡單直觀的例子講解一下,新建一個Test.vue:
<template> <div id='app'> </div></template><script> export default{ name:’Test’, mounted() { }, }</script><style></style>
再建一個Test2.vue:
<template></template><script> export default { name: 'Test2' }</script><style scoped></style>
Test.vue是父組件,Test2.vue是子組件,下面先給Test配置路由,以便在瀏覽器上可以訪問,為Test2定義模板,可以在Test中使用。
在router/index.js中添加下面代碼
import Test from '../components/Test';Vue.use(Router)export default new Router({ mode: ’history’, routes: [{ path: ’/t’, name: ’Test’, component: Test } ]})
在main.js中,添加下面代碼:
import Test2 from './components/Test2';Vue.use(Test2)new Vue({ el: ’#app’, router, components: { App, 'Test2':Test2 }, template: ’<App/>’})
現(xiàn)在在test2頁面寫上這樣一句,
<template><div> {{text2}}</div></template><script> export default { name: 'Test2', data(){ return{ text2:'這是Test2頁面' } } }</script><style scoped></style>
在test中引入test2,同時也定義一個變量text,然后顯示在頁面上,代碼如下:
<template> <div id='app'> {{text1}} <Test2></Test2> </div></template><script> import Test2 from './Test2'; export default{ name:’Test’, components: {Test2}, data(){ return{ text1:'這是Test1頁面' } }, mounted() { }, }</script><style></style>
瀏覽器訪問http://localhost:8080/t,頁面如下:
現(xiàn)在要實現(xiàn)Test2接收Test1的值并顯示:
綁定數(shù)據(jù)用v-bind
<Test2 v-bind:text1='text1'></Test2>
傳的數(shù)據(jù)是Test頁面的text1,命名也是text1,可以不同,但接收時的名字和第一個要相同。
Test2頁面要接收數(shù)據(jù)啊,通過props接收:
props: [’text1’],
接收之后可以把它傳給text2,也可以直接在頁面顯示:
<template><div> {{text2}} {{text1}}</div></template><script> export default { name: 'Test2', props: [’text1’], data(){ return{ text2:'這是Test2頁面' } } }</script><style scoped></style>
接收到text1值了,怎么同步更改呢,需要再綁定一個函數(shù),如下:
<Test2 v-bind:text1='text1' v-on:textChanged='change($event)'></Test2>....methods: { change(msg){ this.text1 = msg; } },
在test2中,將值發(fā)射到textChanged就可以了
mounted() { this.$emit('textChanged','我改了text1的值') }
補充知識:在vue中使用vuex,修改state的值
1、 安裝 vuex
npm install vuex -S
2、在目錄下創(chuàng)建store文件
3、 在store.js編輯一個修改state的方法
然后在mian.js中全局引入
最后在組件中使用
這個的功能是運用mutations 修改state中的值
以上這篇vue實現(xiàn)兩個組件之間數(shù)據(jù)共享和修改操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關文章:
