簡體   English   中英

如何僅使用vue從外部文件將數據加載到vue.js

[英]How to load data into vue.js from an external file using vue only

在下面的這個vue示例中,我試圖僅使用vue從外部js文件中加載“ images”數組。 我嘗試了類似於本文的內容: 如何從Vue.js中的外部文件訪問數據? 但這對我來說並不是很有效(很可能是因為我做錯了明顯的事情)。 非常感謝任何有關如何使該工作有效的建議。

我為您創建了一個codePen,以防您喜歡這樣看。 謝謝! https://codepen.io/FloydGekko/pen/eLoRBQ

<head>
    <style>
        [v-cloak] {
          display: none;
        }

        .imageBlock{
            width:100%;
            margin:10px;
        }
        div.polaroid {
            width:310px;
            height:440px;
            margin:10px;
            background-color: white;
            box-shadow: 6px 4px 8px 0 rgba(0, 0, 0, 0.2), 6px 6px 20px 0 rgba(0, 0, 0, 0.19);
            margin-bottom: 25px;
            border-radius: 18px
        }
        div.container {
            text-align: center;
            padding: 10px 20px;
        }
    </style>
</head>

<body>

<div id="vue" v-cloak>
    <h2 align="center">
        Show
    <select v-model="currentKind" @change="onChange">
        <option v-for="kind, index in kinds" :value="kind" :key="`kind_${index}`">{{kind ? kind : 'kind...'}}</option>
    </select>
    <select v-model="currentColor" @change="onChange">
        <option v-for="color, index in colors" :value="color" :key="`kind_${index}`">{{color ? color : 'color...'}}</option>
    </select>
        and
     <select v-model="currentShape" @change="onChange">
        <option v-for="shape, index in shapes" :value="shape" :key="`kind_${index}`">{{shape ? shape : 'shape...'}}</option>
    </select>
    </h2>

    <isotope
            id="root_isotope"
            ref="isotope"
            :options='options'
            :list="images"
            align="center">
        <div class="polaroid" align="center"
            v-for="(image, index) in images"
            class="imageBlock"
            :key="image.id">
            <a target="_blank"  :href="image.url"><img border="0" :src="image.pic" alt=""
            style="
                border-radius: 20px;
                display: block;
                margin-left: auto;
                margin-right: auto;
                width: 100%;">
            </a>
            <div class="container">
                <a target="_blank"  :href="image.url">
                <h3 align="center">{{image.title}}</h3>
                </a>
            </div>
        </div>
    </isotope>
    <h2 align="center">
        <button @click="reset">Show all</button>
    </h2>
</div>


<script src='https://unpkg.com/vue/dist/vue.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js'></script>
<script src='https://npmcdn.com/isotope-layout@3.0.6/dist/isotope.pkgd.min.js'></script>
<script src='https://rawgit.com/David-Desmaisons/Vue.Isotope/master/src/vue_isotope.js'></script>


<script>
    let currentKind = null;
    let currentColor = null;
    let currentShape = null;

    var vm = new Vue({
        el: '#vue',
        data() {
            return {
                currentKind:'',
                currentColor:'',
                currentShape:'',
                options: {
                    itemSelector: ".imageBlock",
                    getSortData: {
                      id: "id"
                    },
                    sortBy : "id",
                    getFilterData: {
                        Finder: function(itemElem) {
                            let kindSearch = currentKind ? itemElem.kind.indexOf(currentKind) !== -1 : true;
                            let colorSearch = currentColor ? itemElem.color.indexOf(currentColor) !== -1 : true;
                            let shapeSearch = currentShape ? itemElem.shape.indexOf(currentShape) !== -1 : true;
                            return kindSearch && colorSearch && shapeSearch
                        },
                    },
                },

        //THIS IS THE ARRAY IM TRYING TO LOAD FROM AN EXTERNAL FILE
                images: [
                    {
                        id: 1,
                        kind: ['A'],
                        color: ['Green', 'Blue'],
                        shape: ['Square'],
                        pic: 'http://r.ddmcdn.com/s_f/o_1/cx_462/cy_245/cw_1349/ch_1349/w_720/APL/uploads/2015/06/caturday-shutterstock_149320799.jpg',
                        url: 'http://r.ddmcdn.com/s_f/o_1/cx_462/cy_245/cw_1349/ch_1349/w_720/APL/uploads/2015/06/caturday-shutterstock_149320799.jpg',
                        title: 'A',
                    },
                    {
                        id: 2,
                        kind: ['B'],
                        color: ['Green', 'Red'],
                        shape: ['Circle'],
                        pic: 'https://www.kimballstock.com/pix/DOG/05/DOG-05-JE0078-01P.JPG',
                        url: 'https://www.kimballstock.com/pix/DOG/05/DOG-05-JE0078-01P.JPG',
                        title: 'B',
                    },
                ],

            };
        },
        computed: {
            kinds(){
                let allTags = _.flatten(this.images.map(image => image.kind))
                return [''].concat(_.uniq(allTags))
            },
            colors(){
                let allTags = _.flatten(this.images.map(image => image.color))
                return [''].concat(_.uniq(allTags))
            },
            shapes(){
                let allTags = _.flatten(this.images.map(image => image.shape))
                return [''].concat(_.uniq(allTags))
            },
        },
        methods: {
            onChange: function() {
                currentColor = this.currentColor;
                currentShape = this.currentShape;
                currentKind = this.currentKind;

                this.$refs.isotope.filter('Finder');
                this.$refs.cpt.layout('packery');
            },
            reset(){
                currentColor = '';
                currentShape = '';
                currentKind = '';

                this.currentColor = '';
                this.currentShape = '';
                this.currentKind = '';
                this.onChange()
            }
        },
    });
</script>
</body>
</html>

https://codepen.io/FloydGekko/pen/eLoRBQ

它實際上取決於“外部”的含義和“僅Vue”的含義。 如果您可以控制數據,數據的結構和位置,則可以執行@softbear所做的事情-只需在項目中import javascript文件即可。 您可以根據設置以多種方式執行此操作。 他的例子包括

<script src="images.js"></script>

出口的東西沿着

window.images = [{ 'array of images': 'goes here'}]

如果您使用的是Vue,則應該能夠使用引導項目,並直接從源文件中導入該項目。

您可以有一個提供相同結果的后端,並且導入腳本時瀏覽器會自動加載它。

有很多方法,但是結果是相同的。 這里最重要的是,此文件必須declare您的變量,以后應使用。


上面的方法幾乎沒有問題:您無法完全控制何時開始加載數據,也沒有完全控制何時加載數據(有多種方法可以執行此操作,但是更加困難且難看)。 某些跨域服務不允許您直接執行js代碼-它們只能提供數據。

這意味着,如果最終遇到這種情況(例如,連接到動態數據集而不是硬編碼數據集),最好提出請求以加載此數據。 基本上是手動執行瀏覽器可以為您完成的工作。 但是通過這種方式,您可以完全(輕松)地控制何時以及如何完成此操作。

再次有很多方法-如果您在現代瀏覽器中使用最新的JS,則可以使用fetch API或使用一些外部工具,例如axios

我會投票支持第二種方法,盡管它可能會給您的項目增加另一個依賴性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM