假如我们的网页不是完全由vue3开发的,只是部分功能使用了vue3。我们想在vue外面访问vue中定义的变量,该怎么访问呢?
可以通过"app._instance.setupState"来获取vue3中定义的变量。
案例如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue3怎么在setup外面访问setup中定义的变量</title>
</head>
<body>
<div id="app">
{{message}}
<button onclick="changeMessage()">改变</button>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
const { createApp, ref } = Vue;
const app = createApp({
setup() {
const message = ref('hello');
return {
message
}
}
});
app.mount('#app');
function changeMessage(){
app._instance.setupState.message = '你好';
}
</script>
</body>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue3怎么在setup外面访问setup中定义的变量</title>
</head>
<body>
<div id="app">
{{message}}
<button onclick="changeMessage()">改变</button>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
const { createApp, ref } = Vue;
const app = createApp({
setup() {
const message = ref('hello');
return {
message
}
}
});
app.mount('#app');
function changeMessage(){
app._instance.setupState.message = '你好';
}
</script>
</body>
</html>