标签: vue-composition-api

Vue.js 3.0 - 当存储属性值通过组合 API 更改时更新组件 UI

我正在使用 Vue.js 3.0 编写一个 Vue.js 应用程序。我用它来学习组合 API。我不清楚的一件事是当存储值更新时如何有条件地更新我的组件 UI。为了演示我的问题,我创建了这个 fiddle。代码详细在这里:

JavaScript

const store = {
  state: reactive({
    result = null
  }),
  generateNewValue() {
    this.state.result = Math.floor(Math.random() * 10);
  }
};

const MyApp = {
  setup() {
    return {
    }
  }
}
const myApp = Vue.createApp(MyApp)

myApp.component("banner", 
  { 
    template: '<button @click="onGenerateClick">generate</button>',
    setup(props) {
      console.log('setting up...');
    },
    methods: {
      onGenerateClick() {
        store.generateNewValue();
      }
    }
  }
);

myApp.component("content", {
  template: '<div><span>Content</span><button @click="onGenerateClick">generate</button></div>',
  methods: {
    onGenerateClick() {
      store.generateNewValue();
    }
  }  
});

myApp.mount('#my-vue')
Run Code Online (Sandbox Code Playgroud)

超文本标记语言 …

javascript vue.js vuejs3 vue-composition-api

3
推荐指数
1
解决办法
2255
查看次数

使用 Vue 2 Composition API 访问 this.$refs、this.$router、this.$route

您能告诉我如何访问Vue 2 Composition API 设置函数中的this.$refs, this.$router,吗?this.$route有提到的解决方案,context.$root$root不再可用context。请帮忙。

我正在使用带有 Composition API 插件的 Vue 2。似乎useRouteuseRouters不支持Vue 2路由器版本。useRoute并且useRouters可与 Vue-router v4 一起使用。

vue.js vue-router vue-component vuejs2 vue-composition-api

3
推荐指数
1
解决办法
2024
查看次数

Vue 3 组合 API 定义方法的类型安全方式是什么

我正在使用 Vue 的组合 API(在 Vue.js 3 中)并主要在setup(). 虽然通过直接访问我自己的 props ,但我无法以类型安全的方式公开此处定义的函数。setup(props)methods

以下内容有效,但我需要任意转换,因为没有向 TypeScript 公开的方法接口。

<!-- MyComponent.vue -->

<script lang='ts'>
// ...
export default defineComponent({
  setup() {
    // ...
    return {
       publicFunction: async (): Promise<void> => { /* ... */ };
    }
  }
});

</script>
Run Code Online (Sandbox Code Playgroud)
<!-- AppComponent.vue -->

<template>
  <MyComponent ref="my"/>
</template>

<script lang='ts'>

export default defineComponent({
  async setup() {
    const my = ref();

    async func() {
      await (my.value as any).publicFunction(); // <-- gross!
    }

    return { …
Run Code Online (Sandbox Code Playgroud)

typescript vuejs3 vue-composition-api

3
推荐指数
1
解决办法
2183
查看次数

如何使用`&lt;脚本设置&gt;`?

Vue版本:3.0.11

使用以下代码:

<template>
  <button @click="inc">{{ count }}</button>
</template>

<script setup>
  import { ref } from 'vue'

  export const count = ref(0)

  export const inc = () => count.value++
</script>
Run Code Online (Sandbox Code Playgroud)

我有:

ERROR  Failed to compile with 1 error
 error  in ./src/views/HyperScript.vue?vue&type=script&setup=true&lang=js

Syntax Error: TypeError: Cannot read property 'content' of null


 @ ./src/views/HyperScript.vue?vue&type=script&setup=true&lang=js 1:0-293 1:0-293 1:294-576 1:294-576
 @ ./src/views/HyperScript.vue
 @ ./src/router/index.ts
 @ ./src/main.ts
 @ multi (webpack)-dev-server/client?http://192.168.6.175:8080&sockPath=/sockjs-node (webpack)/hot/dev-server.js ./src/main.ts
Run Code Online (Sandbox Code Playgroud)

javascript vue.js vuejs3 vue-composition-api vue-script-setup

3
推荐指数
1
解决办法
5165
查看次数

Vue 3 和 Composition API:v-for 循环中的模板引用错误:仅获取代理

我一直在使用 Vue3.js 和 Vue Cli 开发我的第一个项目,在过去的几个小时里我一直被这段代码困住了。

\n

基本上我想要做的是根据代码的 setup() 部分中创建的对象数组创建一个按钮列表。所有对象还在数组本身中包含自己的引用,我最终将其绑定在模板上。然后,我从每个引用中创建常量,以便我可以在 setup() 中使用它们,但是当我 console.log(btnConvert.value) 时,我得到一个代理,而我的其他引用则没有代理在 v-for 循环内。

\n
    RefImpl\xc2\xa0{_rawValue: Proxy, _shallow: false, __v_isRef: true, _value: Proxy}\n
Run Code Online (Sandbox Code Playgroud)\n

这是 console.log(btnConvert.value) 的扩展版本

\n
Proxy {\xe2\x80\xa6}\n  [[Handler]]: Object\n    get: \xc6\x92 get({ _: instance }, key)\n    has: \xc6\x92 has({ _: { data, setupState, accessCache, ctx, appContext, propsOptions } }, key)\n    ownKeys: (target) => {\xe2\x80\xa6}\n    set: \xc6\x92 set({ _: instance }, key, value)\n  [[Prototype]]: Object\n  [[Target]]: Object\n  [[IsRevoked]]: false\n
Run Code Online (Sandbox Code Playgroud)\n

我尝试了我能想到的一切,但我无法理解官方 Vue 文档。\n有人可以帮助我理解如何使用这些引用检索 DOM 元素吗?\n非常感谢!

\n …

vue.js vue-cli vuejs3 vue-composition-api

3
推荐指数
1
解决办法
8558
查看次数

如何在组合 API 的 setup() 内部使用 $axios Nuxt 模块?

文档说要this.$axios.$get()在 of 内部使用methods/mounted/etc,但是TypeError: _this is undefined在 of 内部调用时会抛出异常setup()$axios与组合 API 兼容吗?

为了澄清一下,我专门谈论 axios nuxt 插件,而不仅仅是一般使用 axios。https://axios.nuxtjs.org/

例如,类似这样的事情会引发上面的错误

export default {
  setup: () => {
    const data = this.$axios.$get("/my-url");
  }
}
Run Code Online (Sandbox Code Playgroud)

javascript vuejs2 nuxt.js vue-composition-api

3
推荐指数
1
解决办法
3343
查看次数

Vue 对计算的 props 变化没有反应

我在我的一个组件中使用 Vue 组合 API,但在让组件根据计算的 prop 更改显示正确的渲染值时遇到一些问题。看来,如果我将 prop 直接输入到组件渲染中,它会按应有的方式做出反应,但当我将它传递给计算属性时,它不会。

我不确定为什么这是因为我期望它在计算属性中也是反应性的?

这是我的代码:

应用程序.vue

<template>
  <div id="app">
    <Tester :testNumber="testNumber" />
  </div>
</template>

<script>
import Tester from "./components/Tester";

export default {
  name: "App",
  components: {
    Tester,
  },
  data() {
    return {
      testNumber: 1,
    };
  },
  mounted() {
    setTimeout(() => {
      this.testNumber = 2;
    }, 2000);
  },
};
</script>
Run Code Online (Sandbox Code Playgroud)

测试器.vue

<template>
  <div>
    <p>Here is the number straight from the props: {{ testNumber }}</p>
    <p>
      Here is the number when it goes through computed (does not …
Run Code Online (Sandbox Code Playgroud)

javascript vue.js vuejs2 vuejs3 vue-composition-api

3
推荐指数
1
解决办法
1271
查看次数

Props watch 在 Vue 组合 api 中不起作用

我有一个state对象作为另一个组件的道具传递。我收到了state预期的结果。然后我将其存储props在 a 中toRef()以进行反应。

我想要发生的是当数据发生state变化时,我希望浏览器中的数据进行更新。现在,数据确实在 vue 开发工具中更新,并且我确实看到了state对象更改,但浏览器不会反映更改,直到我手动刷新浏览器,这是一个不希望的结果。

为什么会发生这种情况:

成分:

<template>
      <div class="show-products">
        <Product
            v-for="data in products"
            :key="data.id"
            :product="data"
        />
      </div>
 </template>

<script>
import {computed, onMounted, toRefs, watch } from "vue";
import {useStore} from "vuex";
    
    export default {
      components: {Product},
      props: {
        state: Object
      },
      setup (props) {
        const store = useStore();
        const products = computed(() => store.getters.getProducts);
    
        let stateRef = toRefs(props).state;
    
        onMounted(() => {
          store.dispatch('getProducts');
        });
    
        watch(stateRef, (currentState, prevState) …
Run Code Online (Sandbox Code Playgroud)

vue.js vuejs3 vue-composition-api

3
推荐指数
1
解决办法
2万
查看次数

提供注入在 vue 3 组合 API 中无法正常工作

我正在使用 Vue 3 组合 api 并通过检索天气数据,async/await fetch并在 Chrome 开发工具中收到 200 响应和请求中的数据。

在接收数据并进行调用的组件中,我有一个provide方法,然后我将inject数据放入另一个输出组件中。问题出在inject组件上。ed 变量的值inject始终为 null,并且不会在 Vue 开发工具中更新,因此我的数据永远不会输出到屏幕。我浏览了文档,代码几乎相同,但我无法让它工作。任何人都可以看到一个明显的问题吗?

接收组件

setup () {
    async function getCurrentWeather () {
      const response = await fetch(`${baseWeatherApiUrl}q=${userInput.value}`);

      userInput.value = null;

      return weatherData.value = await response.json();
    }

    const returnedWeatherData = reactive(weatherData);

    provide('returnedWeatherData', returnedWeatherData);

    return {
      getCurrentWeather,
      userInput,
      weatherData
    }
  }
Run Code Online (Sandbox Code Playgroud)

输出组件

setup () {
    //Provide default of empty object in case no results exist
    const weatherData = inject('returnedWeatherData'); …
Run Code Online (Sandbox Code Playgroud)

vue.js vuejs3 vue-composition-api

3
推荐指数
1
解决办法
1万
查看次数

Vue 3 cli-service 应用程序:当从其他组件导入带有插槽的组件时,出现“在渲染函数之外调用插槽“默认””警告

MCVE

我有一个Tabpane将插槽作为输入的组件。从模板导入后,它会按预期工作。

<Tabpane>
    <div caption="I am div 1">Div 1</div>
    <div caption="I am div 2">Div 2</div>
</Tabpane>
Run Code Online (Sandbox Code Playgroud)

但是,当从其他组件导入时(Composite在示例中),它会触发以下警告:

Slot "default" invoked outside of the render function:
this will not track dependencies used in the slot. Invoke the slot function inside the render function instead. 
Run Code Online (Sandbox Code Playgroud)
Slot "default" invoked outside of the render function:
this will not track dependencies used in the slot. Invoke the slot function inside the render function instead. 
Run Code Online (Sandbox Code Playgroud)

slots vue.js vuejs3 vue-composition-api

3
推荐指数
1
解决办法
8270
查看次数