好了 終于逃不過要搞組件間參數(shù)傳遞 這是我在學(xué)習(xí)vue時(shí)候非常頭疼的一個(gè)問題。由于Vue 2.x以后相比較Vue 1.x而言,升級(jí)變化除了實(shí)現(xiàn)了Virtual-Dom以外,給使用者最大不適就是移除的組件的props的雙向綁定功能。
之前在Vue1.x中利用props的twoWay和.sync綁定修飾符就可以實(shí)現(xiàn)props的雙向綁定功能,但是在Vue2中徹底廢棄了此功能,似乎需要雙向綁定可以自己來實(shí)現(xiàn)。不過人家既然廢除了,肯定有其中的道理,想傳參就單向通信吧。
先來看個(gè)代碼片段:

引入組件 然后components里注冊(cè)一下
//父組件中
<sitelist :site-id="dialogForm.data.site_id" v-on:listenToChildEvent="siteWatch"
class="componentItem"></sitelist>
//子組件中
<template>
<el-form-item label="場(chǎng)地列表">
<el-select v-model="siteId" placeholder="請(qǐng)選擇場(chǎng)地">
<el-option v-for="(item, index) in sitedata" :key="index" v-bind:label="item.title_cn" v-bind:value="item.site_id"></el-option>
</el-select>
</el-form-item>
</template>
<script type="es6">
import {site} from '@/api/general'
export default{
props: ['siteId'],
data() {
return {
//以上通過props接收父組件傳過來的siteid 要注意的是 父組件中的寫法是 xxx-xxx 加橫線分隔 在子組件中接收需要用xxxXxx的駝峰方式接收。
其實(shí)也很簡(jiǎn)單的一個(gè)功能 就是把所有能選擇的場(chǎng)地都封裝一下↓

頁面中

當(dāng)我選擇子組件的select時(shí)...

wtf?!
找來找去 原來問題出在這里了↓
//子組件中html
<el-select v-model="componentSite" placeholder="請(qǐng)選擇場(chǎng)地"> ←就是這個(gè)v-model
<el-option v-for="(item, index) in sitedata" :key="index" v-bind:label="item.title_cn" v-bind:value="item.site_id"></el-option>
</el-select>
//子組件中js
watch: {
siteId: function (params) {
this.componentSite = this.siteId; //現(xiàn)在需要監(jiān)聽siteId的變化 換成這個(gè)componentSite放在v-model里
},
componentSite: function(){
this.$emit("listenToChildEvent", this.componentSite)
}
},
因?yàn)樾枰獙⒏附M件傳來的值重新賦值 不能直接操作父組件傳來的值

頁面中
可以看到問題已經(jīng)得到解決了。
關(guān)于作者
var myproject = {
nickName : "remix_huang",
site : "http://www.itdecent.cn/u/717e2ca57b3f"
}