简体   繁体   English

如何从 vue3 中的设置脚本中获取变量

[英]How do you get variables from the setup script in vue3

How would I access variables declared within the setup script within the none setup script?我将如何访问在无设置脚本中的设置脚本中声明的变量? I attempt to update the message in the example below when something happens within the script tags.当脚本标签中发生某些事情时,我尝试在下面的示例中更新消息。 However, msg just returns undefined, I've looked through the Vue documentation on setup scrips, but there doesn't seem to be any mention of accessing the variable in none setup scripts.但是,味精只是返回未定义,我查看了有关设置脚本的 Vue 文档,但似乎没有提到在无设置脚本中访问变量。

<script setup>

   var msg = 'Hello!';

</script>

<script>

export default {
  data() {
    return {

    };
  },
  mounted(){
   
      // my current attempt to get msg and update it. However, I just get undefined.
      this.msg = 'Something happened inside script tags';
      //or msg = 'Something happened inside script tags';
    
  },

</script>


<template>
  <p>{{ msg }}</p>
</template>

Seems like you are mixing up two syntaxes here - the newer, Composition API (Vue3, setup script) and Options API (Vue2 style, one with data and mounted functions).似乎您在这里混合了两种语法 - 较新的组合 API(Vue3,设置脚本)和选项 API(Vue2 风格,一种具有数据和安装功能)。 While it's still ok to use the Options API syntax, you should only use one of the two.虽然使用 Options API 语法仍然可以,但您应该只使用两者之一。 I suggest reading up on the different syntaxes:我建议阅读不同的语法:

Composition API组成 API

Options API选项 API

The tag is syntactic sugar for THIS type of syntax.标签是这种语法的语法糖。 Everything returned by the setup() function will be made available to the template. setup() function 返回的所有内容都将可用于模板。 If you're using the tag, by default everything is made available.如果您使用标签,默认情况下所有内容都可用。

For the Options API syntax, everything returned by the data function is made available to the template.对于 Options API 语法,数据 function 返回的所有内容都可用于模板。 Delete the entire first tag and try adding the "msg" property to the object returned by the data function and see if it works.删除整个第一个标签并尝试将“msg”属性添加到数据 function 返回的 object 中,看看它是否有效。

  data() {
    return {
        msg: ''
    };
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM