【发布时间】:2022-01-09 05:14:17
【问题描述】:
我正在 Vue 中构建一个带有几个文本区域的网站,它们应该具有来自 Vuex 的 getter 的价值。
这是我的一个不起作用的文本区域:
<textarea
v-model="blogById.htmlCode"
cols="30"
rows="10"
spellcheck="false"
></textarea>
这是我的脚本:
import { mapGetters } from "vuex";
export default {
name: "CodeEditor",
data() {
return {
htmlCode: this.blogPost.htmlCode,
cssCode: "",
jsCode: "",
styleBegin: "<style>",
styleEnd: "</style>",
scriptBegin: "<script>",
scriptEnd: "</" + "script>",
};
},
methods: {
writeCode() {
var doc = document.getElementById("myframe").contentWindow.document;
doc.open();
doc.write(
this.htmlCode +
this.styleBegin +
this.cssCode +
this.styleEnd +
this.scriptBegin +
this.jsCode +
this.scriptEnd
);
doc.close();
},
},
mounted() {
this.writeCode();
let code = this.$refs.htmlCode.value;
},
props: {
id: {
required: true,
},
},
computed: {
...mapGetters({
blogById: "blogById",
}),
blogById() {
return this.blogById(this.id);
},
},
};
最后,这是我的商店:
import { createStore } from 'vuex';
export default createStore({
state: {
cards: [{
title: "Blog 1",
htmlCode: "This is blog 1 htmlCode",
cssCode: "This is blog 1 cssCode",
jsCode: "This is blog 1 jsCode",
index: 1,
},
{
title: "Blog 2",
htmlCode: "This is blog 2 htmlCode",
cssCode: "This is blog 2 cssCode",
jsCode: "This is blog 2 jsCode",
index: 2,
},
{
title: "Blog 3",
htmlCode: "This is blog 3 htmlCode",
cssCode: "This is blog 3 cssCode",
jsCode: "This is blog 3 jsCode",
index: 3,
},
{
title: "Blog 4",
htmlCode: "This is blog 4 htmlCode",
cssCode: "This is blog 4 cssCode",
jsCode: "This is blog 4 jsCode",
index: 4,
},
{
title: "Blog 5",
htmlCode: "This is blog 5 htmlCode",
cssCode: "This is blog 5 cssCode",
jsCode: "This is blog 5 jsCode",
index: 5,
},
{
title: "Blog 6",
htmlCode: "This is blog 6 htmlCode",
cssCode: "This is blog 6 cssCode",
jsCode: "This is blog 6 jsCode",
index: 6,
},
{
title: "Blog 7",
htmlCode: "This is blog 7 htmlCode",
cssCode: "This is blog 7 cssCode",
jsCode: "This is blog 7 jsCode",
index: 7,
},
],
},
getters: {
blogById: (state) => (index) => {
// cast both to Number() to prevent unexpected type-mismatch
return state.cards.find(c => Number(c.index) === Number(index));
},
},
});
有两种可能的解决方案
- v-model 等于一个
data()值并且该值等于一个 getter - v-model 相当于一个 getter
我的目标是使用来自商店 (Vuex) 的数据构建一个代码编辑器。代码编辑器有一个库,其中包含商店中的所有商品,当您单击其中一个时,您会被发送到代码编辑器。
该代码编辑器包含 3 个文本区域(HTML、CSS 和 JS)+ 一个带有预览的 iframe。每个库项目都有自己的 HTML、CSS 和 JS 代码。
【问题讨论】: