关于如何在 vue 中引入和使用 js 中的数据

有时候当一个数组或者对象比较大,且放在了前端,如果将数据放在vue中的data中,就会显得很多。且不方便以后维护,可以当都将这个数据项放在一个js文件中。

这是 js 中的代码,将数据封装在一个函数里面

export function dataInJs() { 
	var user = [
		{ 
			id: 1,
		},
		{ 
			id: 2,
		},
		{ 
			id: 3,
		},
		{ 
			id: 4,
		},
		{ 
			id: 5,
		},
		{ 
			id: 6,
		},
	];
	return user;
}

在vue中引入并使用

<script>
import {  dataInJs } from "./data";
export default { 
	name: "test", //test
	mixis: [],
	components: { },
	props: { },
	data() { 
		return { 
			userList: dataInJs(),
		};
	},
	computed: { },
	watch: { },
	created() { 
		console.log(this.userList);
	},
	mounted() { },
	destroyed() { },
	methods: { },
};
</script>

这是打印结果
《关于如何在 vue 中引入和使用 js 中的数据》

注意:

  1. 引入的方式 import { dataInJs } from "./data";
    import 引入的名字要用花括号括起来,且这个名字要和 js 中函数名一致,
  2. 在data中,将引入过来的数据,传给本地变量,userList: dataInJs()
    变量名后面的数据,实际是js中的函数,所以要加上括号。

除了将数据放在js中,也可以放在一个子组件中,专门用来保存数据。
子组件中的代码

<script>
export default { 
	name: "data", //data
	mixis: [],
	components: { },
	props: { },
	data() { 
		return { 
			userInfo: [{  id: 1 }, {  id: 2 }, {  id: 3 }, {  id: 4 }],
		};
	},
	computed: { },
	watch: { },
	created() { 
		this.$emit("userInfoList", this.userInfo);
	},
	mounted() { },
	destroyed() { },
	methods: { },
};
</script>

父组件中的代码

<template>
	<div class="container">
		<Sub @userInfoList="getUserInfo"></Sub>
	</div>
</template>
<script>
import Sub from "./data.vue";
export default { 
	name: "test", //test
	mixis: [],
	components: {  Sub },
	props: { },
	data() { 
		return { 
			userList: null,
		};
	},
	computed: { },
	watch: { },
	created() { 
		console.log("created");
		console.log("userList", this.userList);
	},
	beforeMount() { 
		console.log("beforeMount");
		console.log("userList", this.userList);
	},
	mounted() { 
		console.log("mounted");
		console.log("userList", this.userList);
	},
	destroyed() { },
	methods: { 
		getUserInfo(data) { 
			console.log(data);
			this.userList = data;
		},
	},
};
</script>

打印的信息
《关于如何在 vue 中引入和使用 js 中的数据》
在子组件中引入数据,要在mounted中才可以获取到数据。

如有错误,欢迎指正,谢谢!
以上内容仅供参考,欢迎大家讨论。

    原文作者:thirteen_king13
    原文地址: https://blog.csdn.net/thirteen_king13/article/details/118330342
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞