Vue.js 通过Vue.extend或“扩展”创建组件时的不同行为;新建Vue()”:视图模型&x27;如果通过新的Vue创建,则无法访问的数据和方法

Vue.js 通过Vue.extend或“扩展”创建组件时的不同行为;新建Vue()”:视图模型&x27;如果通过新的Vue创建,则无法访问的数据和方法,vue.js,vuejs2,vue-component,Vue.js,Vuejs2,Vue Component,我有一个简单的组件您好: {{msg}} 导出默认值{ 姓名:'你好', 道具:{'myprop':String}, 数据(){ 返回{ msg:'欢迎'+this.myprop } }, 方法:{ mymethod:函数(){ 返回“你好” } } } 现在,根据组件的创建方式,可以访问方法和数据。最简单的说明方法是通过测试,请阅读测试中的注释: 从“Vue”导入Vue 从“@/components/Hello”导入Hello 描述('Hello.vue',()=>{ 它('使用Vue扩展

我有一个简单的组件您好:


{{msg}}
导出默认值{
姓名:'你好',
道具:{'myprop':String},
数据(){
返回{
msg:'欢迎'+this.myprop
}
},
方法:{
mymethod:函数(){
返回“你好”
}
}
}
现在,根据组件的创建方式,可以访问方法和数据。最简单的说明方法是通过测试,请阅读测试中的注释:

从“Vue”导入Vue
从“@/components/Hello”导入Hello
描述('Hello.vue',()=>{
它('使用Vue扩展',()=>{
const Constructor=Vue.extend(您好)
const vm=new构造函数({propsData:{myprop:'fromtest via propsData'}})。$mount()
//以下三个期望都会成功
expect(vm.$el.querySelector('.hello h1').textContent)
.to.equal('欢迎通过propsdata进行测试')
expect(vm.myprop).to.equal('fromtest via propsdata')
expect(vm.mymethod()).to.equal('hi there'))
})
它('使用新的Vue',()=>{
const vm=新的Vue(
{
模板:“”,
组件:{'hello':hello}
}).$mount()
//以下期望成功
expect(vm.$el.querySelector('.hello h1').textContent)
.to.equal('Welcome from template in test')
//以下两个预期将失败
expect(vm.mymethod()).to.equal('hi there'))
expect(vm.myprop).to.equal('来自测试中的模板')
})
})
我怎样才能使最后两个期望工作


谢谢。

您必须先注册自定义组件。有两种方法可以做到这一点:

  • 全球注册:

    //寄存器
    Vue.component('hello'{
    模板:“”,
    // ...
    });
    //创建您的根实例
    const vm=新的Vue({
    el:“#root”//假设root最终呈现“hello”组件
    });
    
    Vue.js文档:

    注册后,组件可以在实例的模板中用作自定义元素[…]在实例化根Vue实例之前,确保组件已注册

  • 通过本地注册:

    //声明
    var hello={
    模板:“”,
    // ...
    };
    //创建根实例,在“组件”中注册所有内容
    const vm=新的Vue({
    组件:{'hello':hello}
    });
    
对于您的情况,前者似乎更合适,因为您希望保持SOC完整,只需测试组件的功能。

好的,我找到了解决方案。 要获得最后2个期望值,请执行以下操作:

expect(vm.$children[0].mymethod()).to.equal('hi there')
expect(vm.$children[0].myprop).to.equal('from template in test')

回想起来,很明显,因为我们在一个div中添加了组件。

对不起,什么是SOC?您能以这样的方式为测试2提供完整的代码吗?最后2个期望成功了。我没有看到:(以下期望在测试2中失败:expect(vm.mymethod()).to.equal('hi there')expect(vm.myprop).to.equal('from template in test'))我的观点是,在测试2中,第一个预期成功,所以我假设组件安装正确,不是吗?只有在测试2中,预期2和3由于不明显的原因失败。我真的不知道。你必须调试代码和/或发布一些错误,以便我们知道什么不起作用。