如何将变量作为参数发送到单个文件组件中的方法?
How to send variable as a parameter to a method in single file component?
我正在尝试将变量中的所有 \n
替换为 <br>
。为什么我不能将变量作为函数参数从模板发送到方法?控制台显示 Uncaught TypeError: Cannot read property 'replace' of undefined
.
我认为它调用了 n2br 方法,但不能将变量作为参数发送。
有大佬知道怎么解决这个问题吗?
<template>
<div id="iletisim" class="page">
<div>{{ n2br(iletisim.address) }}</div>
</div>
</template>
<script>
export default {
name: "iletisim",
data() {
return {
iletisim: ""
}
},
methods: {
fetch: function() {
this.$http.get(this.site.apiPath + this.site.currentLangCode + "/" +this.$route.params[1]).then(response => {
this.iletisim = response.body.content;
},
response => {
// error callback
});
n2br: function(text) {
text = text.replace(/(?:\r\n|\r|\n)/g, '<br />');
return text;
}
},
beforeMount () {
this.fetch()
}
}
</script>
嗯,我认为您不需要老老实实地发送。听起来你需要一个计算 属性.
假设您的获取方法设置数据 属性 iletisim
.
在您的模板中,您可以这样做:
<div>{{ computedIletisim }}</div>
然后在您的组件中,在方法之后添加计算
export default {
...
methods: {
...
},
computed: {
computedIletisim: function() {
return this.iletisim.address.replace(/(?:\r\n|\r|\n)/g, '<br />');
}
}
...
}
最初实例化时,您的 'iletism' 数据是一个字符串。该字符串没有 属性 地址。所以 iletism.address 是未定义的。
当它到达您的 n2br 函数时,它会调用 undefined.replace。哪个不存在,因此替换不存在未定义的错误。
所以要么在 n2br 方法中对此进行保护,要么为 iletism 设置一个默认值,以便地址存在但为空字符串。
您可以使用计算 属性 完成同样的事情,但同样的,您需要在数据或计算方法中设置的基本情况。
我正在尝试将变量中的所有 \n
替换为 <br>
。为什么我不能将变量作为函数参数从模板发送到方法?控制台显示 Uncaught TypeError: Cannot read property 'replace' of undefined
.
我认为它调用了 n2br 方法,但不能将变量作为参数发送。
有大佬知道怎么解决这个问题吗?
<template>
<div id="iletisim" class="page">
<div>{{ n2br(iletisim.address) }}</div>
</div>
</template>
<script>
export default {
name: "iletisim",
data() {
return {
iletisim: ""
}
},
methods: {
fetch: function() {
this.$http.get(this.site.apiPath + this.site.currentLangCode + "/" +this.$route.params[1]).then(response => {
this.iletisim = response.body.content;
},
response => {
// error callback
});
n2br: function(text) {
text = text.replace(/(?:\r\n|\r|\n)/g, '<br />');
return text;
}
},
beforeMount () {
this.fetch()
}
}
</script>
嗯,我认为您不需要老老实实地发送。听起来你需要一个计算 属性.
假设您的获取方法设置数据 属性 iletisim
.
在您的模板中,您可以这样做:
<div>{{ computedIletisim }}</div>
然后在您的组件中,在方法之后添加计算
export default {
...
methods: {
...
},
computed: {
computedIletisim: function() {
return this.iletisim.address.replace(/(?:\r\n|\r|\n)/g, '<br />');
}
}
...
}
最初实例化时,您的 'iletism' 数据是一个字符串。该字符串没有 属性 地址。所以 iletism.address 是未定义的。
当它到达您的 n2br 函数时,它会调用 undefined.replace。哪个不存在,因此替换不存在未定义的错误。
所以要么在 n2br 方法中对此进行保护,要么为 iletism 设置一个默认值,以便地址存在但为空字符串。
您可以使用计算 属性 完成同样的事情,但同样的,您需要在数据或计算方法中设置的基本情况。