vue中報錯 Property or method "xxxx" is not defined on the instance but referenced during render. Make

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>裏面使用則不需要定義,直接使用即可。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章