【发布时间】:2020-05-09 05:24:37
【问题描述】:
我是 Vue.js 的新手(具有计算机科学和编程方面的背景,包括交互式 Javascript 网页),因为我是一名教师,所以我有一个测验网站用来给我的学生布置作业。
我的代码库很乱,所以我决定将整个东西迁移到 Vue,我的想法是我可以为每种单独的问题类型使用一个组件——关注点分离等等。
但是,我似乎无法找到一种方法来动态生成适当的组件并将它们包含在我的页面中。
这是我的框架的简化版本,有两种问题类型。如果我将组件直接包含在 HTML 中,它们就可以正常工作。
Vue.component("Freetext",{
props: ["prompt","solution"],
data : function() {return {
response:""
}},
methods : {
check : function () {
if (this.solution == this.response) {
alert ("Correct!");
app.nextQuestion();
} else {
alert ("Try again!");
}
}
},
template:'<span><h1>{{prompt}}</h1> <p><input type="text" v-model="response"></input></p> <p><button class="LG_checkbutton" @click="check()">Check</button></p></span>'
})
Vue.component("multi",{
props : { prompt: String,
options : Array,
key_index : Number // index of correct answer
},
data : function() {return {
response:""
}},
methods : {
check : function (k) {
if (k == this.key_index) {
alert ("Correct!");
app.nextQuestion();
} else {
alert ("Try again!");
}
}
},
template:'<span><h1>{{prompt}}</h1><button v-for="(v,k) in options" @click="check(k)">{{v}}</button></span>'
})
</script>
<div id="app">
<Freetext prompt="Type 'correct'." solution="correct"></freetext>
<multi prompt="Click the right answer." :options='["right","wrong","very wrong"]' :key_index=0></multi>
</div>
<script>
var app = new Vue({
el: "#app",
data : {
questions:[ {type:"Multi",
prompt: "Click the right answer.",
options:["right","wrong","very wrong"],
key:0},
{type:"Freetext",
prompt:"Type 'correct'.",
solution:"correct"}
],
question_number:0
},
methods : {
nextQuestion : function () {
this.question_number ++;
}
}
})
</script>
但我想要做的是动态生成 div app 的内容,基于使用数据成员 app.question_number 作为 app.questions 的索引,以及所指示问题的 .type 成员(即app.questions[app.question_number].type)
如果我尝试制作表单的应用程序:
{{question}}
</div>
<script>
//...
computed : {
question : function () {
var typ = this.questions[this.question_number].type;
return "<"+typ+"></"+typ+">";
}
...我只是得到纯文本,它没有被解析为 HTML。
如果我从控制台尝试document.getElementById("app").innerHTML = "<multi prompt='sdf'></multi>";,标签会显示在DOM 检查器中,并且不会被Vue 处理,即使我调用app.$forceUpdate()。
有没有办法解决这个问题?
【问题讨论】:
-
也许您需要再次阅读 Vue 的工作原理 - 可能有更好的方法(就 Vue 的工作原理而言)来完成您想要实现的目标
-
您也可以像现在一样将所有组件添加到 html 中,但添加
v-if="type=='FreeText'"并仅按问题类型显示正确的组件。 -
你也可以使用
v-bind:is像这个例子 jsfiddle.net/chrisvfritz/o3nycadu from vue docs "dynamic components" -
<component :is=...正是我所需要的。谢谢。不知道为什么,但我查看的所有 Vue 资源都非常不清楚。我的代码现在运行良好。
标签: javascript vue.js vue-component