我被困在传递Vue组件。
当调用Vue组件中的单击事件时,我想将Vue组件传递给其他组件。我试过'this'但它返回null。
如果有人可以帮助我。这是我的代码。提前致谢。
<template>
...
<button type="button" class="confirmBtn" @click="$util.routerReplace(this, '/')">
<span>confirm</span>
</button>
...
</template>
util.js
function routerReplace (foo, path) {
console.log(foo) // Now return null => Vue Component
console.log(path) // path
}
我的理解是,使用this
作为上下文来评估模板中直接指定的事件处理程序中的所有标识符。因此,您将this.this
传递给未定义的routerReplace
。
如果您使用组件方法作为事件处理程序,它可以工作:
var Component = {
template: '<button type="button" @click="onClick">Confirm</button>',
methods: {
onClick: function() {
this.$util.routerReplace(this, '/')
},
},
}
Vue.prototype.$util = {};
Vue.prototype.$util.routerReplace = function(component, path) {
console.log(component, path);
};
new Vue({
el: '#app',
components: {
MyComponent: Component,
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<my-component/>
</div>