大家好,又見面了,我是你們的朋友全棧君。
1.父向子傳值props
父元件:<child :inputName=”name”>
子元件:
(1)props: {
inputName: String,
required: true
}
(2)props: [“inputName”]
2.子元件向父元件傳值$emit
子元件:
<span>{
{childValue}}</span>
<!– 定義一個子元件傳值的方法 –>
<input type=”button” value=”點選觸發” @click=”childClick”>
export default {
data () {
return {
childValue: ‘我是子元件的資料’
}
},
methods: {
childClick () {
this.$emit(‘childByValue’, this.childValue)
}
}
}
父元件
<!– 引入子元件 定義一個on的方法監聽子元件的狀态–>
<child v-on:childByValue=”childByValue”></child>
methods: {
childByValue: function (childValue) {
// childValue就是子元件傳過來的值
this.name = childValue
}
}
}
3.父元件調用子元件的方法通過ref
在DOM元素上使用refs可以迅速進行dom定位,類似于(“selectId”)
使用this.$refs.paramsName能更快的擷取操作子元件屬性值或函數
子元件:
methods:{
childMethods() {
alert(“I am child’s methods”)
}
}
父元件: 在子元件中加上ref即可通過this.$refs.method調用
<template>
<div @click=”parentMethod”>
<children ref=”c1″></children>
</div>
</template>
<script>
import children from ‘components/children/children.vue’
export default {
data(){
return {
}
},
computed: {
},
components: {
‘children’: children
},
methods:{
parentMethod() {
console.log(this.$refs.c1) //傳回的是一個vue對象,可以看到所有添加ref屬性的元素
this.$refs.c1.childMethods();
}
},
created(){
}
}
</script>
4.可以通過parent和children擷取父子元件的參數
我們可以使用children[i].paramsName 來擷取某個子元件的屬性值或函數,children傳回的是一個子元件數組

![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIwIjNx8CX39CXy8CXycXZpZVZnFWbp9zZlBnauczM3YjMlZWN1EGM5MWOkhDM1MTO2AjN3EWNkJTO0UTYvw1NzUzMyIDOtUGall3LcVmdhNXLwRHdo9CXt92YucWbpRWdvx2Yx5yazF2Lc9CX6MHc0RHaiojIsJye.jpeg)
那麼子元件怎麼擷取修改父元件的資料内容?這需要使用$parent


5.vue 全局事件(eventBus)
在main.js裡:window.eventBus = new Vue();//注冊全局事件對象
在檔案清單裡 <span >{
{ item }}<button @click=”down(item)”>下載下傳</button></span>

另一元件的監聽

6.兄弟之間的傳值Vuex
在state裡定義資料和屬性
在 mutations裡定義函數fn,在頁面通過
this.$store.commit(‘fn’,params)來觸發函數,Vuex在這裡不做詳細介紹了
釋出者:全棧程式員棧長,轉載請注明出處:https://javaforall.cn/145206.html原文連結:https://javaforall.cn