javascript - 如何使用 Vue 实例中的 Global Mixin 方法
问题描述
假设我有以下情况,使用一个 Global Mixin 用 Vue 创建一个全局 helper 方法:
import Vue from "vue";
Vue.mixin({
methods: {
replaceString: function (word) {
return word.toLowerCase().replace(/\W/g, '');
}
}
});
let vm = new Vue({
methods: {
doSomething: function() {
console.log(this.replaceString('Hello World'); //helloword
}
}
});
我知道我可以在组件及其子组件内部的其他方法中调用该方法。但是如何从 Vue 实例“vm”中调用 mixin 方法“replaceString”呢?我尝试使用“vm.replaceString”,但一直返回“未定义”。
解决方案
对您的代码几乎没有更改,并且可以正常工作:
- 您应该更改 mixin 的定义(var mixin 而不是 Vue.mixin)
将 mixin 导入新的 vue 组件(mixins = [mixin])
import Vue from "vue"; var mixin = { methods: { replaceString: function (word) { return word.toLowerCase().replace(/\W/g, ''); } } }; let vm = new Vue({ mixins: [mixin] methods: { doSomething: function() { console.log(this.replaceString('Hello World'); //helloword } } });
推荐阅读
- php - 如何从逗号分隔值mysql php中选择和获取
- python-3.x - 我可以阅读我已经在 Xlsxwriter 的单元格中写的内容吗?
- android - 我正在尝试将我的 Android 项目连接到 Firebase 实时数据库,但它总是失败。请帮我找出错误是什么
- vuejs2 - 如何删除双引号?
- php - Pjax 在 Yii2 上的 gridview 搜索上重新加载页面
- c++ - 字符串不会在拆分时更新其值
- java - 如何在 Intelli J 中设置 JAVA_HOME 环境变量
- javascript - 谷歌地图中的滑动标记给出错误谷歌未定义
- angular - 将html表导出到excel Angular 6
- sqlite - Xamarin Forms:如何按时间排序从本地数据库中选择所有项目