vue.js - VueJs:在自定义组件上绑定“v-on”以替换现有组件
问题描述
为了简化页面的样式,我想创建一堆迷你组件,并利用属性在 VueJs 中的合并方式。例如,这里有一个最小的 js 文件也托管在这个JSFiddle上:
Vue.component('my-button', {
template: '<button style="font-size:20pt;"><slot></slot></button>'
})
var app = new Vue({
el: "#app",
data: {
message: "world",
},
methods: {
sayHello: function () {
alert("Hello");
}
}
})
然后在我的html中我只想使用<my-button>
而不是button
:
<div id="app">
Hello {{message}} <my-button @click="sayHello" style="color:red;">Style works, but not click</my-button> <button v-on:click="sayHello" style="color:red;">Both works</button>
</div>
不幸的是,似乎合并了属性,但没有合并侦听器,所以这意味着我不能v-on:click
在我的新按钮上做......有什么办法让它成为可能吗?
谢谢!
-- 编辑 -- 我看到了 Boussadjra Brahim 的建议 using .native
,并且它有效,但后来我发现这个链接解释了为什么它不是一个很好的做法以及如何使用v-on="$listeners"
将所有听众映射到特定的子按钮。但是,我尝试将我的模板更改为:
template: `<button style="font-size:20pt;" v-on="$listeners"><slot></slot></button>`,
但我收到一个错误:
Vue warn: Property or method "$listeners" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option."
这是JSFiddle。
解决方案
您的小提琴不起作用,因为您使用的是旧版本的 Vue,$listeners
它是在 Vue 2.4.0 中添加的。
这是一个演示:
Vue.component('my-button', {
template: '<button style="color: red" v-on="$listeners"><slot/></button>'
})
new Vue({
el: '#app',
methods: {
sayHello() {
alert('Hello')
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<my-button @click="sayHello">Custom Button</my-button>
<button @click="sayHello">Ordinary Button</button>
</div>
推荐阅读
- json - 用jq提取json里面的json
- java - Two threads updating the same object, will it work? java
- r - 循环使用 ggplot 绘制箱线图
- python - 在 Pandas 中一次对多个数据帧进行排序
- python - Flask flashes 出现在开发服务器上,但不使用 uWSGI/Nginx
- create-react-app - 如何避免使用 react-scripts/create-react-app 违反 ESLint 导致构建失败?
- c++ - C++链表非成员函数反向打印
- bash - 包含单引号或双引号的 Bash 变量扩展
- python - 在 C++ 中增加 pybind11 句柄的 ref_count
- python - Flask FileAllowed 验证器未检测到错误 - 如何编写自定义验证器?