思路: 通過調用函數 把 組件實例this 傳遞 到 被應用的 js文件里
實例:
文件結構
在SendThis.vue 文件中引用 了modalConfig.js
import modalConfig from './modalConfig'
我們只要在 modalConfig.js文件里定義個函數和一個變量(用來存this)即可
//用來獲取 調用此 js的vue 組件 實例 (this) let vm = null; const sendThis = ( _this )=> { vm = _this; }; export default { sendThis, //暴露函數 drawer: { //這里是測試代碼, 假設這里會有其他暴露的變量 columns: [ { title: 'Name', key: 'name' }, { title: 'Age', key: 'age' }, { title: 'Address', key: 'address' }, { title: '操作', render: (h, params)=>{ return h('a',{ on: { click: ()=>{ /*如果這里要使用 sendThis 實例 this*/ // this.handleShowDrawer(); // console.log(vm); //可以拿到組件 實例 了 vm.handleShowDrawer(); //調用組件實例中的函數 } } }, '抽屜'); } } ] }, }
在 SendThis.vue 問中定義的handleShowDrawer函數
methods: { //這個函數會在 modalConfig.js 文件中觸發 handleShowDrawer(){ this.showDrawer = true; }, //把 modalConfig.js的 drawer.columns 賦值 給 this.columns1 handleTableColumn(){ let { columns } = modalConfig.drawer; this.columns1 = columns; } },
下面我們只要在鈎子函數中 調用 modalConfig.js 的 sendThis 方法, 把this傳過去即可了
mounted() { //發送this 到 js 文件里 modalConfig.sendThis(this); }
此時: modalConfig.js 中 的 vm 就是 SendThis.vue 文件中的 this了。
---------------------------------------
還用一種方法是你把 一些屬性和方法掛在到 vue實例原型上了, 可以在 某個js文件中這樣拿到vue 實例。
詳見 ---》 https://www.cnblogs.com/taohuaya/p/10296420.html