我正在一个网站上工作,我的经典多页由刀片模板提供支持,但我想使用vuejs组件来满足最动态的需求。
它运行正常,但我找不到一种方便的方法来声明VueJs为组件解析的容器。
我想在很多地方使用很多组件,但由于与<script>
标签冲突,我无法将大型主容器声明为VueJs容器。
如果我这样做,我会收到如下错误:- Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as <script>, as they will not be parsed.
我目前在app.js
文件中执行类似的操作:
new Vue({
el: '#need-components-1'
});
new Vue({
el: '#need-components-2'
});
new Vue({
el: '#need-components-3'
});
我真的不喜欢它,我希望能够将整个内容声明为VueJs-able,或者至少使用容器的公共类或属性。每次我想为组件使用新的位置时,我需要添加一个新的id。此外,每次找不到元素时,VueJs都会发布控制台错误,因为很明显它们并非总是被加载。
有没有优雅/方便的方法呢?
由于
答案 0 :(得分:1)
使用一些元素是根Vue的标识符,然后在页面加载时迭代在页面上找到的元素并为它们创建Vue。
这是一个例子。
console.clear()
const vues = document.querySelectorAll("[data-vue]")
for (let v of vues)
new Vue({el: v, data: {message: "Hello from Vue"}})
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div data-vue="true">
<h2>{{message}}</h2>
</div>
<h4>Some other page content</h4>
<div data-vue="true">
<h2>{{message}}</h2>
</div>
<h4>Some other page content</h4>
<div data-vue="true">
<h2>{{message}}</h2>
</div>
&#13;
显然,如果它应该与Vue到Vue不同,你需要找到一种方法将适当的数据与正确的Vue结合起来。