日常积累,欢迎指正
源代码在
vue-project 的分支 dev-005
,可以直接获取代码运行查看/** 父组件 */
export default {
methods: {
searchEnter:function(){
console.log('search enter')
}
}
}
/** 子组件 */
export default {
name: "HomeHeader",
methods: {
enterFn: function() {
this.$parent.searchEnter()
}
}
}
<input
placeholder="请输入关键字"
@keyup.enter="enterFn" />
如果有向父组件传参数的需求的话只需要添加参数即可
export default {
name: "Search",
methods: {
enterFn: function() {
this.$parent.searchEnter(this.inputText)
}
},
data() {
return {
inputText: ""
};
}
}
<input
placeholder="请输入关键字"
v-model="inputText"
@keyup.enter="enterFn"
/>
可以在调用时直接传参吗?
子组件
export default {
name: "HomeHeader",
methods: {
enterFn: function() {
this.$emit('enter');
}
}
}
<input @keyup.enter="enterFn" />
<input
@keyup.enter="$emit('enter')"
/>
父组件
export default {
name: "HomeHeader",
methods: {
searchEnter: function() {
console.log("search enter");
}
}
}
<Search @enter="searchEnter" />
如果要传参数的话
子组件
export default {
name: "HomeHeader",
methods: {
enterFn: function() {
this.$emit('enter',this.inputText);
}
},
data() {
return {
inputText: ""
};
}
}
<input
@keyup.enter="enterFn"
v-model="inputText"
/>
<input
@keyup.enter="$emit('enter',inputText)"
v-model="inputText"
/>
父组件
export default {
name: "HomeHeader",
methods: {
searchEnter: function(value) {
console.log("search enter");
console.log(value)
}
}
}
<Search @enter="searchEnter" />
我是从 react 过来的,这种方式与 react 子组件向父组件传值(子组件调用父组件方法)非常相似
子组件
<input
placeholder="请输入关键字"
v-model="inputText"
@keyup.enter="enterFn"
/>
<input
placeholder="请输入关键字"
v-model="inputText"
@keyup.enter="enter"
/>
export default {
name: "Search",
props: {
enter: {
type: Function,
default: null
}
},
methods: {
enterFn: function() {
if (this.enter) {
this.enter()
this.enter(this.inputText) // 如果要传参数直接在这里传递就好了
}
}
},
data() {
return {
inputText: ""
};
}
};
父组件
<Search :enter="searchEnter"/>
import Search from "../Search/index.vue";
export default {
name: "HomeHeader",
components: {
Search
},
methods: {
searchEnter: function() {
console.log("search enter");
}
}
};
如果想要传递参数的话
export default {
name: "Search",
props: {
enter: {
type: Function,
default: null
}
},
methods: {
enterFn: function() {
if (this.enter) {
this.enter(this.inputText) //
/**
* 在这里传递或直接内联调用 enter 方法传递
*
*
*/
}
}
},
data() {
return {
inputText: ""
};
}
};
父组件
<Search :enter="searchEnter"/>
import Search from "../Search/index.vue";
export default {
name: "HomeHeader",
components: {
Search
},
methods: {
searchEnter: function(value) {
console.log("search enter")
console.log(value)
}
}
};