我正在用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));
},
},
});有两种可能的解决方案
data()值,该值等于getter。
我的目标是用存储区(Vuex)的数据构建一个代码编辑器。代码编辑器有一个库,其中包含存储的所有项目,当您单击其中一个项目时,您将被发送到代码编辑器。
该代码编辑器包含3个文本区域(HTML、CSS和JS) +一个带有预览的iframe。库项都有自己的HTML、CSS和JS代码。
发布于 2021-12-02 18:07:57
我看到两个错误:
blogById与Vuex getter blogById具有完全相同的名称。因此,您可能无意地在此组件中覆盖Vuex getter。将其更改为getBlogById() computed: {
...mapGetters({
blogById: "blogById",
}),
blogById() {
return this.blogById(this.id);
},
},v-model是读/写,所以您试图写入一个只用于读取的值。Getter用于读取,突变用于写入Vuex状态中的变量。将其更改为:value="getBlogById.htmlCode",以便它是正确的,因为您只从getter.中读取。
<textarea
v-model="blogById.htmlCode"
cols="30"
rows="10"
spellcheck="false"
></textarea>https://stackoverflow.com/questions/70204088
复制相似问题