VS Code TreeDataProvider简单示例

2019-09-27  本文已影响0人  Gavin_c980

示例结构

实例结构

package.json

contributes中增加如下片段

"views": {
    "explorer": [
        {
            "id": "TreeView",
            "name": "TreeView"
        }
    ]
}

完整代码如下所示

{
    "name": "test",
    "displayName": "test",
    "description": "test treeview",
    "version": "0.0.1",
    "engines": {
        "vscode": "^1.37.0"
    },
    "categories": [
        "Other"
    ],
    "activationEvents": [
        "*"
    ],
    "main": "./out/extension.js",
    "contributes": {
        "commands": [
            {
                "command": "extension.helloWorld",
                "title": "Hello World"
            }
        ],
        "views": {
            "explorer": [
                {
                    "id": "TreeView",
                    "name": "TreeView"
                }
            ]
        }
    },
    "scripts": {
        "vscode:prepublish": "npm run compile",
        "compile": "tsc -p ./",
        "watch": "tsc -watch -p ./",
        "postinstall": "node ./node_modules/vscode/bin/install",
        "test": "npm run compile && node ./node_modules/vscode/bin/test"
    },
    "devDependencies": {
        "typescript": "^3.3.1",
        "vscode": "^1.1.28",
        "tslint": "^5.12.1",
        "@types/node": "^10.12.21",
        "@types/mocha": "^2.2.42"
    }
}

extension.ts

import * as vscode from 'vscode';
import {DataProvider} from './dataProvider';

export function activate(context: vscode.ExtensionContext) {
    vscode.window.registerTreeDataProvider("TreeView", new DataProvider());
}

export function deactivate() {}

dataProvider.ts

import { TreeDataProvider, Event, TreeItem, TreeItemCollapsibleState, ProviderResult } from "vscode";

export class DataProvider implements TreeDataProvider<DataItem> {
    onDidChangeTreeData?: Event<DataItem | null | undefined> | undefined;
    data: DataItem[];

    constructor() {
        this.data = [
            new DataItem('line1', [new DataItem('line1-sub1'), new DataItem('line1-sub2')]),
            new DataItem('line2', [new DataItem('line2-sub1'), new DataItem('line2-sub2')]),
            new DataItem('line3', [new DataItem('line3-sub1'), new DataItem('line3-sub2')])
        ];
    }

    getTreeItem(element: DataItem): TreeItem | Thenable<TreeItem> {
        return element;
    }

    getChildren(element?: DataItem | undefined): ProviderResult<DataItem[]> {
        if (element === undefined) {
            return this.data;
        }
        return element.children;
    }
}


class DataItem extends TreeItem{
    public children: DataItem[] | undefined;

    constructor(label: string, children?: DataItem[] | undefined) {
        super(label, children === undefined ? TreeItemCollapsibleState.None : TreeItemCollapsibleState.Collapsed);
        this.children = children;
    }
}

执行效果

执行效果
上一篇下一篇

猜你喜欢

热点阅读