我是 Vue Js 的新手,想用它来过滤一些下拉列表等。考虑到我已经拥有 View 模型中下拉列表的所有数据,我想将该数据传递给Vue 实例,然后我可以在其中使用 Vue 过滤下拉菜单。
我试过将数据放入一个简单的 div 中,这样我就可以将其选择到 Vue 实例中,但它不起作用。一定有更好的方法。我是否必须单独回调服务器以填充 Vue 实例?
代码片段只有一个简单的数组,我似乎也无法加载它。
最终想退出这个 View 模型
@model MyApp.CatalogViewModels.ViewModel
脚本在这里...
new Vue({
el: "#app",
data: {
categories: ["one", "two"]
}
,
methods: {
loadCategories() {
$('#modelData.items').forEach(item => this.categories.push(item))
}
},
created() {
this.loadCategories()
}
})
标记...
<div id="app">
<div id="modelData" items=['apple','orange','pear']></div>
<div>
<div>
<ul>
<li v-for="item in categories">
{{ item }}
</li>
</ul>
</div>
最佳答案
首先要解决这个问题:
执行此操作的“最佳实践”方法是在客户端从后端服务器/API 检索数据,而不是通过模板引擎将数据添加到属性。这样做实际上违背了 Vue
的目的。
为什么停止将该数据添加到 items
属性?为什么不通过 Razor 将它添加到列表中呢? -- 这就是为什么在 Vue
中使用模板引擎没有意义的原因..
此外,将 jQuery
与 Vue
一起使用是多余的,不需要。如果你正确配置您的设计。有时他们在一起玩得不好,这取决于你在做什么或你使用的框架,你是否使用 Webpack 等。虽然,大多数时候它应该没问题(但再次,完全不必要)。
综上所述:
你可以做这样的事情来从 items
属性中获取数据。我在我的回答中提供了 2 个例子,其中一个比另一个更容易......记住,这个当您尝试从 DOM 中获取数据时,数据是文字字符串格式。
编辑: 将一堆 replace
更改为使用 regex
以清理它
new Vue({
el: "#app",
data: {
categories: ["one", "two"],
categories2: ["three", "four"]
},
methods: {
loadCategories() {
//$('#modelData.items').forEach(item => this.categories.push(item))
document
.getElementById("modelData")
.getAttribute("items")
.replace(/[\[\]']+/g, "")
.split(",")
.forEach(x => {
this.categories.push(x);
});
},
loadCategories2() {
document
.getElementById("modelData2")
.getAttribute("items")
.split(",")
.forEach(y => {
this.categories2.push(y);
});
}
},
created() {
this.loadCategories();
this.loadCategories2();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<div id="app">
<div id="modelData" items=['apple','orange','pear']></div>
<ul>
<li v-for="item in categories">
{{ item }}
</li>
</ul>
<br/>
<hr/>
<br/>
<small>Easier this way</small>
<div id="modelData2" items="apple, orange, pear"></div>
<ul>
<li v-for="item in categories2">
{{ item }}
</li>
</ul>
</div>
关于asp.net-mvc - Vue.Js - 如何从 MVC View 模型将数据加载到 Vue 实例中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56450352/