04. 逻辑统一放到一个文件
于2022-11-14 18:47:20发布
47
当一些变量与函数,被多个页面用到时,你应该把这些逻辑都放到一个文件里,重复使用。(vue2只能用mixins实现)
例子
index.js
import {
ref,
reactive
} from "vue";
export const citys = reactive([{
id: 0,
name: '深圳'
}, {
id: 1,
name: '广州'
}]);
export const id = ref(1);
export const cityChange = () => {
console.log(`你选中的城市是:${citys[id.value].name}`);
}
html
<template>
<div>
<select v-model="id" @change="cityChange">
<option v-for="(item, key) in citys" :key="key" :value="item.id">
{{ item.name }}
</option>
</select>
</div>
</template>
<script setup>
import { citys, id, cityChange } from "../utils/index";
</script>
运行效果