網上找了幾種方法,下面這兩種最實用,最明了
方法一:父組件方法返回是字符串或數組時用這種方法
子組件:
<template>
<button @click="submit">提交</button>
</template>
<script>
export default {
methods: {
submit: function () {
// 子組件中觸發父組件方法ee並傳值1
this.$emit('ee', '1')
}
}
}
</script>
父組件:
<template>
<editor id="editor" class="editor" @ee="cc"></editor>
</template>
<script>
export default {
data() {
return {
text: ''
}
},
methods: {
cc: function (str) {
if(str === 1){
this.text = '中國'
} else {
this.text='美國'
}
}
}
}
</script>
方法二:父組件方法返回是boolean類型時用這種方法
子組件:
<template> <button @click="submit">提交</button> </template> <script> export default { props: { validate: { type: Function, default: null } }, methods: { submit: function () {
// 子組件觸發父組件方法goValidate並傳值data let data = { newName:"張三", oldName:"李四" } if (!that.validate(data)) { console.log('新名:'+data.newName) } } } } </script>
父組件:
<template>
<editor id="editor" class="editor" :validate="goValidate"></editor>
</template>
<script>
export default {
methods: {
goValidate: function (data) {
let newName = data.newName
if (newName.length < 1) {
layer.msg('命名不能為空,請重新輸入!', { icon: 7 })
return false
}
return true
}
}
}
</script>
