【问题标题】:How can i get properties from template如何从模板中获取属性
【发布时间】:2020-01-22 12:54:46
【问题描述】:

在向服务器发送有关数据的请求之前,我可以从模板中获取属性吗? 这是我的模板:

<box-component inline-template>
<div>
    <div class="loading" v-if="Loading">  Loading ...  </div>
    <div  v-if="Result">
        <ul>
            <li> {{ Result.FirstProp }} </li>
            <li> {{ Result.FourthProp }} </li>
        </ul>
    </div>
</div>

这是我的组件:

let BoxComponent = {
data() {
    return {            
        Result: null,
        Loading: true
    };
},
created: function () {
    this.Update();
},
methods: {
    Update: function () {
        this.Loading = true;    
        axios.post("#SERVER_URL#")
            .then(response => {
                this.Loading = false;
                this.Result = response.data;
            });
         }
}
}
 Vue.component('box-component', BoxComponent);

效果很好!问题是服务器响应包含更多数据。服务器响应:

{
    "FirstProp": "first",
    "SecondProp": "second"
     ...
    "HundredthProp": "hudredth"
}

我无法修改响应(其他项目也使用此响应)。但是,如果我能够从模板(在本例中为 FirstProp 和 FourthProp)发送属性列表,则服务器端给我过滤后的响应,其中仅包含这些属性,因为最佳响应如下所示:

{
    "FirstProp": "first",
    "FourthProp": "fourth"
}

所以,问题是:我该怎么做?

我可以在 Vue 对象中找到它吗?

我可以将模板加载为字符串变量,但我想避免 regex hack。

更新:

In this case, BoxTemplate call server side without "filters"

This is the optimal case, when js get the variables, that the template use, and call with them the server side. In this case, in the response there are only that variables, what template really use

【问题讨论】:

  • 到底是什么问题,这里没有动态。您在组件中使用了FirstProp 和FourthProp,所以我不明白为什么您不能在提供给您的答案中这样做。
  • 我必须对不同的项目使用相同的组件。另一个项目可能会使用此模板调用组件:
    • {{ Result.FifthProp }}
    • {{ Result.ThirdProp }}
    我可以使用 mixin 并设置不同项目的所有数据,但不太灵活
  • 还是不明白,那不是动态的,如果你真的在模板中编码这些道具,那么你就知道你需要哪些道具了。我认为这不是您的“真实”场景,因此您的问题可能存在问题。
  • 有两个项目。它们使用相同的组件(BoxComponent.js),它们调用相同的服务器端。但是项目使用具有不同变量的不同模板。我需要用当前模板变量调用服务器端
  • 在我的例子中,有近百个项目退出,服务器在响应中提供了大约 200 个变量。这就是为什么需要 js 使用当前变量调用服务器的原因。我无法在每个项目的“data(){}”中设置变量名称,但是当组件调用服务器时,我必须知道模板中存在哪些变量。我不知道,我怎么能在 vuejs 中做到这一点。

标签: vue.js vuejs2 vue-component


【解决方案1】:

我不知道如何设置您的后端,但您可以在数据中拥有其他属性:

data() {
    return { 
        listOfProperty: [
            'FirstProp',
            'FourthProp',
        ],
...

并使用它的列表将数据发送到服务器。

【讨论】:

  • 感谢您的回复。问题是数据必须是动态的。多个项目可以使用不同的模板调用同一个组件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多