vue中使用imort導入函數後使用出錯
在vue
中使用import
模塊導入了一個function
,然後在html中使用了之後,控制檯報瞭如下錯誤
Property or method "XXXX" is not defined on the instance but referenced during render. Make sure that this property is reactive,
either in the data option, or for class-based components, by initializing the property.
注意,是在template
裏面使用了這個函數,如果是在script
中使用就不會出現這個錯誤。
解決辦法就是把這個函數從新在data
裏面定義一個函數。
Example
// test.js
const testF = () => {
console.log('test')
}
export default testF
// index.vue
import testF from './test.js'
data() {
return {
test: testF // 這裏把`testF`函數賦值給`test`
}
}
<template>
<button @click="test">Click me</button> // 使用賦值之後的`test`就不會出錯了
<template>
總結: 如果要在template
裏面使用import
導入的東西,需要在data
裏面定義一下,如果在<script>
裏面使用則不需要定義,直接使用即可。