網上找了幾種方法,下面這兩種最實用,最明瞭html
方法一:父組件方法返回是字符串或數組時用這種方法數組
子組件:this
<template> <button @click="submit">提交</button> </template> <script> export default { methods: { submit: function () { // 子組件中觸發父組件方法ee並傳值1 this.$emit('ee', '1') } } } </script>
父組件:spa
<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類型時用這種方法code
子組件:htm
<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>
父組件:blog
<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>