vue 的 computed 相关的一个问题,求助

2019-09-02 23:19:18 +08:00
 Hopetree

但愿这个图能显示

情况如图所示,这个计算属性会在 sctext 变动时触发,实际上也的确会这样,但是我在 HTML 中使用{{ suggestion }}发现是空的,但是 console 日志会刷新值,所以很奇怪,为甚返回不到值?

如果图挂了,看源码:

<template>
    <div>
    	...	方便查看所以省略其他
        <p>{{ suggestion }}</p>
    </div>
</template>

<script>
export default {
    data() {
        return {
            // 从 store 里面读取数据并使用
            sctype: "",
            scdata: {},
            sctypelist: [],
            sctext: "",
        };
    },
    created() {
        // 设置默认值
        var default_type = this.$store.getters.searchTypes[0];
        this.sctype = default_type;
        this.sctypelist = this.$store.getters.searchTypes;
        this.scdata = this.$store.state.searchList[default_type];
    },
    computed: {
        suggestion: function() {
            var a = ''
            this.$axios
                .get("/baidu/su", { params: { wd: this.sctext } })
                .then(ret => {
                    var json_str = ret.data.match(/s:(\[.*\])}\);/);
                    if (json_str) {
                        var json_str = json_str[1];
                    }
                    console.log(json_str);
                    a = json_str
                });
            return a
        }
    },
    methods: {
        // 选择表单变化的时候同步数据
        changedata: function(command) {
            this.sctype = command;
            this.scdata = this.$store.state.searchList[command];
        }
    }
};
</script>

<style scoped>
img {
    width: 1.2rem;
    margin: 0rem 0.2rem -0.2rem 0rem;
}
</style>

7783 次点击
所在节点    Vue.js
42 条回复
mikoshu
2019-09-03 17:02:58 +08:00
@Biwood
@shintendo
emmm 确实是 估计大家一开始都没想那么多 以为直接给 suggestion 加 async 然后在 promise 的位置 await 一下 再 return 就好了 (包括我也是,已经是习惯把 await 当成是同步了,是有点想当然了)因为毕竟是语法糖 这样会导致 computed 根本无法使用
supuwoerc
2019-09-03 17:05:36 +08:00
终于见到我会的问题了(滑稽)

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/597355

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX