如何从vanillaJS访问/更改Vue组件属性



我有一个用Vue CLI制作的Vue 2项目,我计划将其作为一个库分发,最好是通过某种包装脚本抽象掉依赖项和Vue语法。我想允许这种交互:

// mount the component on a plain JS webpage
const myComponent = new MyComponent('#my-component');
// handle events from the component in vanilla JS
myComponent.on('load', someHandler);
// (A.) call a component method and get a return value
const processedData = myComponent.process(123);
// (B.) access/mutate reactive component data properties
myComponent.setMessage('Hello world!');

我试着把";构建目标";构建Vue文档中提到的库或Web组件。我可以很好地装载库组件并处理事件,但它没有提到我如何与Vue VM外部的组件数据交互(请参见注释AB(。

如何在普通JS中从Vue VM外部访问Vue组件方法和数据属性?

要访问虚拟机之外的Vue组件属性(和方法(,您可以使用;模板ref";像这样:

const vm = new Vue({
components: {
MyComponent,
},
template: `
<my-component
ref="myComponent"
/>
`,
}).$mount('#mount-element");

然后你可以这样调用它的方法:

vm.$refs.myComponent.someFunction();

您将获得返回的值,它将按预期访问/更改VM内的响应属性。

要使用原始问题中描述的类语法,我们可以创建一个简单的类来包装vue组件:

// import the component built by Vue CLI with the "library" build target
// (puts `MyComponent` in the global namespace)
import './MyComponent.umd.min.js'; 
import Vue from 'https://unpkg.com/vue@2/dist/vue.esm.browser.min.js';
export default class {
constructor(mountElement) {
// mount vue VM with a template ref to access its properties
const thisClass = this;
this.vm = new Vue({
components: {
MyComponent,
},
template: `
<my-component
ref="myComponent"
/>
`,
}).$mount(mountElement);
this.component = this.vm.$refs.myComponent;
}
// define methods that could call this.component's functions
someFunction() {
// do stuff
return this.component.someFunction()
}
}

它似乎运行得很好。一个可能的改进是使用不同的工具构建组件库,因为Vue CLI v3(带有Vue v2项目(不能输出ESM模块文件,所以我们能做的最好的事情就是全局定义UMD模块。

最新更新