草庐IT

javascript - 在 Vue 文件中创建根 Vue 实例

coder 2024-07-15 原文

有没有办法让 .vue 文件负责在单文件组件模式中创建自己的 Vue 实例?

这是 Vue 文件。

// MyComponent.vue
<template><div>Hello {{ name }}!</div></template>

<script>
const Vue = require('vue');

// what would usually be exports default
const componentConfig = {
    name: "my-component",
    props: {
        name: String,
    },
};

function create(el, props) {
    const vm = new Vue({
        el,
        render(h) {
            return h(componentConfig, { props });
        });
    vm.$mount();
    return vm;
}

module.exports = { create };
</script>

然后是一些JS文件中的用法:

// index.js
const MyComponent = require('./MyComponent.vue');

const el = '.container';
const props = {
    name: 'Jess',
};

MyComponent.create(el, props);
</script>

当我执行上述操作时,出现无法找到模板的错误。

[Vue warn]: Failed to mount component: template or render function not defined.

found in

---> <MyComponent>
       <Root>

本能地,我不明白 Vue 编译器如何能够神奇地推断出(从脚本标签内)我想要引用上面声明的模板......所以......是的。是否有关于为什么我不能这样做的解释,或者关于如何让它工作的想法?

最佳答案

您所描述的是通过 Webpack 和 Vue Loader 在预编译步骤中完成的. Vue 编译器实际上并不解析 Single File Components . Vue 编译器可以解析的是组件选项对象中提供的模板。因此,如果您提供 template componentConfig 中的选项反对您的示例将起作用。否则,您将不得不通过 Webpack 和 Vue Loader 的预编译步骤来解析单个文件组件的模板。为此,您必须符合 SFC 结构 defined in the spec .这是摘录..

Template

  • Each *.vue file can contain at most one <template> block at a time.
  • Contents will be extracted and passed on to vue-template-compiler and pre-compiled into JavaScript render functions, and finally injected into the exported component in the <script> section.

Script

  • Each *.vue file can contain at most one block at a time.
  • The script is executed as an ES Module.
  • The default export should be a Vue.js component options object. Exporting an extended constructor created by Vue.extend() is also supported, but a plain object is preferred.
  • Any webpack rules that match against .js files (or the extension specified by the lang attribute) will be applied to contents in the <script> block as well.

为了让你的具体例子工作你可以重写main.js像这样的文件..

const MyComponent = require("./MyComponent.vue");

const el = ".container";
const data = {
  name: "Jess"
};

MyComponent.create(el, data);

还有你的MyComponent.vue文件(这也可能是一个 js 文件,正如下面提到的@Ferrybig)..

<script>
const Vue = require('vue');

function create(el, data) {
  const componentConfig = {
    el,
    name: "my-component",
    data,
    template: `<div>Hello {{ name }}!</div>`
  };
  const vm = new Vue(componentConfig);
  return vm;
}

module.exports = { create };
</script>

查看此 CodeSandbox

或者,如果您更喜欢渲染函数,您的 MyComponent.vue看起来像这样..

<script>
const Vue = require('vue');

function create(el, data) {
  const componentConfig = {
    el,
    name: "my-component",
    data,
    render(h) { return h('div', 'Hello ' + data.name) } 
  };
  const vm = new Vue(componentConfig);
  return vm;
}

module.exports = { create };
</script>

CodeSandbox


最后要记住的一件事:在任何组件中,您都可以使用模板或渲染函数,但不能像示例中那样同时使用两者。这是因为其中一个会覆盖另一个。例如,请参阅 JSFiddle Vue boilerplate并注意如何 when you add a render function模板被覆盖。这可以解释您遇到的错误。 render 函数优先,但您为它提供了一个组件的选项对象,该对象不提供要呈现的模板。

关于javascript - 在 Vue 文件中创建根 Vue 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52882583/

有关javascript - 在 Vue 文件中创建根 Vue 实例的更多相关文章

  1. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  2. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  3. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  4. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  5. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

  6. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  7. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  8. ruby-on-rails - 如何使用 instance_variable_set 正确设置实例变量? - 2

    我正在查看instance_variable_set的文档并看到给出的示例代码是这样做的:obj.instance_variable_set(:@instnc_var,"valuefortheinstancevariable")然后允许您在类的任何实例方法中以@instnc_var的形式访问该变量。我想知道为什么在@instnc_var之前需要一个冒号:。冒号有什么作用? 最佳答案 我的第一直觉是告诉你不要使用instance_variable_set除非你真的知道你用它做什么。它本质上是一种元编程工具或绕过实例变量可见性的黑客攻击

  9. ruby 正则表达式 - 如何替换字符串中匹配项的第 n 个实例 - 2

    在我的应用程序中,我需要能够找到所有数字子字符串,然后扫描每个子字符串,找到第一个匹配范围(例如5到15之间)的子字符串,并将该实例替换为另一个字符串“X”。我的测试字符串s="1foo100bar10gee1"我的初始模式是1个或多个数字的任何字符串,例如,re=Regexp.new(/\d+/)matches=s.scan(re)给出["1","100","10","1"]如果我想用“X”替换第N个匹配项,并且只替换第N个匹配项,我该怎么做?例如,如果我想替换第三个匹配项“10”(匹配项[2]),我不能只说s[matches[2]]="X"因为它做了两次替换“1fooX0barXg

  10. Ruby 写入和读取对象到文件 - 2

    好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信

随机推荐