当从同一个JS文件中引入基础类型变量(number、string等)时:
// shared.js
export let count = 1
export let name = "test"
// A.vue
import { count, name } from './shared.js'
count = 2 // 不会影响B.vue中的count
name = "new" // 不会影响B.vue中的name
// B.vue
import { count, name } from './shared.js'
console.log(count) // 仍然是1
console.log(name) // 仍然是"test"
对象、数组等引用类型变量共享同一个内存地址:
// shared.js
export const obj = { value: 1 }
export const arr = [1, 2, 3]
// A.vue
import { obj, arr } from './shared.js'
obj.value = 2 // 会影响B.vue
arr.push(4) // 会影响B.vue
// B.vue
import { obj, arr } from './shared.js'
console.log(obj.value) // 2
console.log(arr) // [1, 2, 3, 4]
使用Vue的响应式API(ref/reactive)时:
// shared.js
import { ref, reactive } from 'vue'
export const count = ref(1)
export const state = reactive({
value: 1,
name: 'test'
})
// A.vue
import { count, state } from './shared.js'
count.value = 2 // 会响应式影响B.vue
state.value = 2 // 会响应式影响B.vue
// B.vue
import { count, state } from './shared.js'
// 能够实时观察到A.vue中的修改